package com.cunyme;

import java.io.IOException;
import java.util.Map;

import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class cuny_me extends Activity implements Runnable
{
    ProgressDialog dialog;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        

        


        // Obviously we can change exactly what functionality we are/aren't implementing later on; I apologize for
        // not thinking to mention this before I began...
        
        SQLiteDatabase cuny_meDB = null;
        
        cuny_meDB = openOrCreateDatabase("cuny_me.db", Context.MODE_PRIVATE, null);
        
        cuny_meDB.execSQL("CREATE TABLE IF NOT EXISTS cookies_table (category TEXT, cookies BLOB)");
        cuny_meDB.execSQL("CREATE TABLE IF NOT EXISTS user_table (username TEXT, password TEXT)");
        
        // For blackboard & schedule data
        // Currently making entries for Primary Key, course name, course ID (a number associated with the class,
        // parsed from the URL), Announcements, Course Information, Course Materials, Assignments,
        // Instructor, My Grades, and class schedule
        
        // The course ID is the only unique element we need for each class; the rest of each web address is the same
        // for every class
        cuny_meDB.execSQL("CREATE TABLE IF NOT EXISTS classes_table (_ID integer primary key autoincrement, " +
        		"course_id TEXT, course_name TEXT, announcements TEXT, course_info TEXT, course_materials TEXT, " +
        		"assignments TEXT, instructor TEXT, my_grades TEXT, class_schedule TEXT)");
        
        // Several entries, such as semester bills, and awards (and I think transcripts too, somehow) can have multiple
        // pages.  To handle this, I will add an additional column, which I will tentatively call "type," to distinguish
        // the different bills/awards for each semester.  So we will need multiple rows after all.
        // Currently making entries for Primary Key, type, e-mail, transcripts, semester bills, and awards
        cuny_meDB.execSQL("CREATE TABLE IF NOT EXISTS esims_table (_ID integer primary key autoincrement, " +
        		"type TEXT, email TEXT, transcripts TEXT, semester_bills TEXT, awards TEXT)");
        
        cuny_meDB.close();
        
        // Set up login button and login listener
		Button myLoginButton = (Button)findViewById(R.id.login_button);
	    myLoginButton.setOnClickListener(myLoginButtonListener);
	    
        
        // Set up skip button and login listener
		Button mySkipButton = (Button)findViewById(R.id.skip_button);
	    mySkipButton.setOnClickListener(mySkipButtonListener);  
    }
    @Override
	public void onConfigurationChanged(Configuration newConfig) {
		// TODO Auto-generated method stub
		super.onConfigurationChanged(newConfig);
	}
	OnClickListener myLoginButtonListener = new OnClickListener()
	{
		public void onClick(View v)
		{
			// TODO Auto-generated method stub
		    // prepare the dialog box
			// Take what user types in text boxes and assigns it to
			// strings
			EditText user = (EditText)findViewById(R.id.user);
			EditText passwd = (EditText)findViewById(R.id.passwd);
			String username = user.getText().toString();
			String password = passwd.getText().toString();
			
			// If username or password fields are blank, program doesn't
			// even TRY to connect.  Note that you can't compare strings with ==.
			if (username.equals(""))
			{
				Toast.makeText(getApplicationContext(), "Must enter username.", Toast.LENGTH_SHORT).show();
			}
			else if (password.equals(""))
			{
				Toast.makeText(getApplicationContext(), "Must enter password.", Toast.LENGTH_SHORT).show();	
			}
			else
			{
				dialog = new ProgressDialog(cuny_me.this);

				// make the progress bar cancelable
				dialog.setCancelable(true);
				
				// set a message text
				dialog.setMessage("Signing in...");
				
				// show it
				dialog.show();
				
				Thread thread = new Thread(cuny_me.this);
				thread.start();
			}
		}
    };
    public void run()
    {
		EditText user = (EditText)findViewById(R.id.user);
		EditText passwd = (EditText)findViewById(R.id.passwd);
		String username = user.getText().toString();
		String password = passwd.getText().toString();
		// Jsoup requires all connections to be made
		// within try/catch blocks.
		try
		{						
			// Connect to CUNY portal using username and password
			// specified in text boxes, and assign resulting
				// page to a document object
				Connection portal_conn = Jsoup.connect("https://portal.cuny.edu/portal/site/cuny/login/index.jsp").data("userid", username, "password",  password, "Submit223", "++Log+In++"); 
				org.jsoup.nodes.Document portal_doc = portal_conn.timeout(10*1000).post();
				Map <String, String> portal_cookies = portal_conn.response().cookies();
				// This "element" section captures the first instance
				// in the resulting web site encased in a <b> tag.
				// If the username and password supplied successfully
				// log you on, the text encased in this element
				// is the string "My page."  If the username/password
				// combination is invalid, the text encased in this
				// element is an "invalid username" message.
				// If it doesn't say "My Page," a pop up message is
				// displayed and the user remains on the page.
				// Otherwise, the user is transferred to the main menu.
				if ( portal_cookies.get("portalErrorCookie").equals("Authentication failed. Please enter a valid username and password.") )
				{
					dialog.dismiss();
					invalid_combo.sendEmptyMessage(0);
				}	
				else
				{
					//We store the portal cookies for connecting to blackboard/esims
					// The first argument of this intent statement is the current page,
					// and the second is the destination page.
					
			        SQLiteDatabase cuny_meDB = null;
			        cuny_meDB = openOrCreateDatabase("cuny_me.db", Context.MODE_PRIVATE, null);
			        
			        // Right now, I'm just deleting and replacing the data in the tables.  Eventually, we're going to want
			        // to do some more sophisticated things with the data, I suppose.
			        cuny_meDB.execSQL("DELETE FROM \"user_table\"");
			        cuny_meDB.execSQL("DELETE FROM \"cookies_table\"");
			        
			        // Placing username, password, and portal cookies in table.  This is not exactly how the guy did
			        // database management in the videos, but using actual SQL code made more sense to me.  We can do
			        // something different for the final product if someone has a better idea.
			        cuny_meDB.execSQL("INSERT INTO \"user_table\" (username, password) VALUES (\"" + username + "\", \"" + password + "\");");
			        cuny_meDB.execSQL("INSERT INTO \"cookies_table\" (category, cookies) VALUES (\"portal\", \"" + portal_cookies + "\");");
			        
			        // Sometimes, the emulator produces an error if you don't close the database at the end of each activity.
			        cuny_meDB.close();

			       success_handler.sendEmptyMessage(0);	
				}
			}
			catch (IOException e)
			{
				// TODO Auto-generated catch block
				// If the connection fails, we end up here.
				failure_handler.sendEmptyMessage(0);
				e.printStackTrace();
			}    
	}
    
    private Handler success_handler = new Handler()
    {
    	@Override
    	public void handleMessage(Message msg)
    	{
    		dialog.dismiss();
		    navigate.sendEmptyMessage(0);

    	}
    };
    private Handler navigate = new Handler()
    {
    	@Override
    	public void handleMessage(Message msg)
    	{
	        // Going to main menu
			Intent gotoMainMenu = new Intent(cuny_me.this, MainMenu.class);
			startActivity(gotoMainMenu);
    	}
    };
    private Handler failure_handler = new Handler()
    {
    	@Override
    	public void handleMessage(Message msg)
    	{
			dialog.dismiss();
			Toast.makeText(getApplicationContext(), "Unable to Establish Connection.", Toast.LENGTH_SHORT).show();	

    	}
    };
    private Handler invalid_combo = new Handler()
    {
    	@Override
    	public void handleMessage(Message msg)
    	{
			Toast.makeText(getApplicationContext(), "Invalid Username/Password Combination", Toast.LENGTH_SHORT).show();
		}
		
    };
    OnClickListener mySkipButtonListener = new OnClickListener()
	{
		public void onClick(View v)
		{
			// TODO Auto-generated method stub
	        // Going to main menu
			Intent gotoMainMenu = new Intent(cuny_me.this, Skipmenu.class);
			startActivity(gotoMainMenu);	
		}
	};
}